import java.util.Comparator;
import java.util.PriorityQueue;

class GreaterIntComp implements Comparator<Integer> {
    @Override
    public int compare(Integer o1, Integer o2) {
        return o2 - o1;
    }
}
class Solution {
    public int[] smallestK(int[] arr, int k) {
        if(null == arr || k <= 0)
            if(k <= 0) {
                return new int[k];
            }
        GreaterIntComp greaterCmp = new GreaterIntComp();
        PriorityQueue<Integer> maxHeap = new PriorityQueue<>(greaterCmp);
//先将前K个元素，创建大根堆
        for(int i = 0; i < k; i++) {
            maxHeap.offer(arr[i]);
        }
        //从第K+1个元素开始，每次和堆顶元素比较
        for (int i = k; i < arr.length; i++) {
            int top = maxHeap.peek();
            if(arr[i] < top) {
                maxHeap.poll();
                maxHeap.offer(arr[i]);
            }
        }
//取出前K个
        int[] ret = new int[k];
        for (int i = 0; i < k; i++) {
            int val = maxHeap.poll();
            ret[i] = val;
        }
        return ret;
    }
}

